<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-11-05
 * Time: 16:37
 */

namespace App\Http\Controllers\Api\V1\Manager\Activity;


use App\Exports\UniversalExport;
use App\Http\Controllers\Controller;
use App\Models\ActivityLuck;
use App\Models\ActivityLuckDetail;
use App\Models\ActivityLuckDetailLog;
use App\Models\Order;
use App\Models\Red;
use App\Models\RedRole;
use App\Models\UserHome;
use App\Models\UserIntegralRedLog;
use App\Models\VipLog;
use DateTime;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class RedController extends Controller
{
    private $namespace = "App\Http\Controllers\Api\V1\Manager\Activity\RedController";

    public function index(Request $request)
    {
        $red = RedRole::first();
        $red['redList'] = Red::orderBy('sort', 'asc')->orderBy('id', 'desc')->get()->toArray();
        return $this->apiResponse($red);
    }

    public function store(Request $request)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $data = $request->only('detail');
        if (!$data['detail']) {
            return $this->apiResponse('', config('errorLiu.NOTCANSHUID'));
        }
        RedRole::where('redRoleId', '!=', 0)->update($data);
        //添加管理员日志开始
        $url = $this->namespace . "/store";
        $title = "修改";
        $content = "修改了红包规则为【" . $data['detail'] . "】";
        $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "红包模块", $title, $content, $request->getClientIp());
        //添加管理员日志结束
        return $this->apiResponse(true);
    }

    public function update(Request $request)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $redRole = RedRole::first();
        if ($redRole['status']) {
            $content = "禁用";
            RedRole::where('redRoleId', '!=', 0)->update(['status' => 0]);
        } else {
            $num = Red::count();
            if(!$num){
                return $this->apiResponse('', config('errorLiu.HONGBAOSHULIANGZUISHAOWEICAIKEI'));
            }
            $content = "启用";
            RedRole::where('redRoleId', '!=', 0)->update(['status' => 1]);
        }
        //添加管理员日志开始
        $url = $this->namespace . "/update";
        $title = "修改";
        $content .= "了红包活动";
        $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "红包模块", $title, $content, $request->getClientIp());
        //添加管理员日志结束
        return $this->apiResponse(true);
    }

    public function redDetail(Request $request)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $id = $request->id;
        $data = $request->only("redName", 'redImage', 'price', 'integral', 'sort', 'num');
        if (!isset($data['redName']) || !isset($data['price']) || !isset($data['integral'])) {
            return $this->apiResponse('', config('errorLiu.NOTCANSHUID'));
        }
        if ($id) {
            $title = "修改";
            $content = "修改了id为【".$id."】红包奖励为【".json_encode($data)."】";
            Red::where('id', $id)->update($data);
        } else {
            $id = Red::insertGetId($data);
            $title = "新增";
            $content = "添加了id为【".$id."】红包奖励为【".json_encode($data)."】";
        }
        //添加管理员日志开始
        $url = $this->namespace . "/redDetail";
        $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "红包模块", $title, $content, $request->getClientIp());
        //添加管理员日志结束
        return $this->apiResponse(true);
    }

    public function destroy(Request $request, $redId)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $redRole = RedRole::first();
        if ($redRole['status']) {
            $num = Red::count();
            if($num == 1){
                return $this->apiResponse('', config('errorLiu.HONGBAOSHULIANGZUISHAOWEICAIKEI'));
            }
        }
        Red::where('id', $redId)->delete();
        //添加管理员日志开始
        $url = $this->namespace . "/destroy";
        $title = "修改";
        $content = "删除了id为【".$redId."】的红包,其内容为【".json_encode($redRole)."】";
        $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "红包模块", $title, $content, $request->getClientIp());
        //添加管理员日志结束
        return $this->apiResponse(true);
    }

    public function redLog(Request $request)
    {

        $userId = $request->userId;
        $userPhone = $request->userPhone;
        $nickname = $request->nickname;
        $status = $request->status;
        $createStartTime = $request->createStartTime;
        $createEndTime = $request->createEndTime;
        $pageSize = $request->pageSize;

        $sql = UserIntegralRedLog::select('t1.id', 't1.userId', 't2.phone as userPhone', 't2.nickname', 't1.redName', 't1.redNum', 't1.createTime', 't1.status')
            ->from((new UserIntegralRedLog())->getTable() . ' as t1')
            ->leftJoin((new UserHome())->getTable() . ' as t2', 't1.userId', '=', 't2.id');
        $ids = $request->ids;
        $idList = [];
        if (isset($ids)) {
            $ids = explode(';', $ids);
            foreach ($ids as $v) {
                $idList[] = $v;
            }
        }
        if (isset($idList[0])) {
            $sql->whereIn('t1.id', $idList);
        }
        if (isset($userId)) {
            $sql->where('t1.userId', $userId);
        }
        if (isset($userPhone)) {
            $sql->where('t2.phone', 'like', "%$userPhone%");
        }
        if (isset($nickname)) {
            $sql->where('t2.nickname', 'like', "%$nickname%");
        }
        if (isset($status)) {
            $sql->where('t1.status', $status);
        }
        if (isset($createStartTime)) {
            $sql->where('t1.createTime', '>=', $createStartTime." 00:00:00");
        }
        if (isset($createEndTime)) {
            $sql->where('t1.createTime', '<=', $createEndTime." 23:59:59");
        }
        if (isset($request->excel)) {
            $redLogList = $sql->orderByDesc('t1.createtime')
                ->get()
                ->toArray();
            $title = ['用户id', '用户手机号', '用户名称', '红包名称', '兑换金额', '兑换时间', '打款状态'];
            $data = [];
            $status = [
                'ENTER' => "已入账",
                'WAIT' => "待入账",
                'PAST' => "已过期",
            ];
            foreach ($redLogList as $value) {
                $redDetail = [];
                $redDetail[] = $value['userId'];
                $redDetail[] = $value['userPhone'];
                $redDetail[] = $value['nickname'];
                $redDetail[] = $value['redName'];
                $redDetail[] = $value['redNum'];
                $redDetail[] = $value['createTime'];
                $redDetail[] = $status[$value['status']];
                $data[] = $redDetail;
            }
            //return var_dump($data);
            return Excel::download(new UniversalExport($data, $title), "红包兑换明细" . date("ymdHis") . '.xlsx');
        }
        $redLogList = $sql->orderByDesc('t1.createtime')
            ->paginate($pageSize)
            ->toArray();
        $data['redLogList'] = $redLogList['data'];
        $data['totalNum'] = $redLogList['total'];
        return $this->apiResponse($data);
    }
}